{% extends "layui/admin/base.html" %}
{% block title %}导航网站 - 分类管理{% endblock %}

{% block content %}
    <blockquote class="layui-elem-quote">
        <p><a href="/admin/v2"><i class="layui-icon layui-icon-home"></i> 首页</a>
            <i class="layui-icon layui-icon-next"></i> 分类管理</p>
    </blockquote>
    <div class="layui-panel">
        <br>
        <div class="layui-card">
            <div class="layui-card-header">
                <h1>分类管理</h1>

            </div>
            <div class="layui-card-body">
                <table id="categoryTable" lay-filter="categoryTableFilter"></table>
            </div>
        </div>
        <!-- 表格工具栏 -->
        <script type="text/html" id="toolbar">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" id="addCategoryBtn">
                    <i class="layui-icon layui-icon-add-circle-fine"></i> 添加分类
                </button>
                <button class="layui-btn layui-btn-sm layui-bg-blue" id="reload">
                    刷新
                    <i class="layui-icon layui-icon-down layui-font-12"></i>
                </button>
            </div>
        </script>
    </div>
{% endblock %}

{% block scripts %}
    <script>
        layui.use(['table', 'layer', 'form'], function () {
            const table = layui.table;
            const layer = layui.layer;
            const form = layui.form;
            const $ = layui.jquery;

            // 初始化表格
            table.render({
                elem: '#categoryTable',
                id: 'categoryTable',  // 注意要设置 ID，方便 reload
                toolbar: '#toolbar',
                defaultToolbar: ['filter', 'print', 'exports'],
                data: [],
                cols: [[
                    {field: 'id', title: 'ID', width: 80},
                    {field: 'name', title: '名称'},
                    {field: 'description', title: '描述'},
                    {title: '操作', width: 180, align: 'center', toolbar: '#operationBar'}
                ]],
                page: false
            });

            // 加载分类数据
            function loadCategoryData() {
                $.ajax({
                    url: '/api/categories',
                    type: 'GET',
                    dataType: 'json',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    },
                    success: function (res) {
                        if (res.code === 0) {
                            table.reload('categoryTable', {
                                data: res.data
                            });
                        } else {
                            layer.msg(res.msg || '加载失败', {icon: 2});
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg('请求失败: ' + error, {icon: 2});
                    }
                });
            }

            loadCategoryData();  // 初始加载

            // 添加分类弹窗
            $('#addCategoryBtn').on('click', function () {
                layer.open({
                    type: 1,
                    title: '添加分类',
                    area: ['500px', '300px'],
                    content: `
                <form class="layui-form" id="addCategoryForm" style="padding: 20px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" required lay-verify="required" placeholder="请输入分类名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">描述</label>
                        <div class="layui-input-block">
                            <input type="text" name="description" placeholder="请输入分类描述" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="submitAdd">提交</button>
                            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                        </div>
                    </div>
                </form>
            `
                });

                form.render();
                form.on('submit(submitAdd)', function () {
                    fetch('/api/categories', {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer ' + localStorage.getItem('token')
                        },
                        body: new FormData(document.getElementById('addCategoryForm'))
                    }).then(res => res.json()).then(res => {
                        if (res.code === 0) {
                            layer.msg('添加成功');
                            layer.closeAll();
                            loadCategoryData();
                        } else {
                            layer.msg(res.msg || '添加失败');
                        }
                    });
                    return false;
                });
            });

            // 编辑与删除操作
            table.on('tool(categoryTableFilter)', function (obj) {
                const data = obj.data;
                if (obj.event === 'edit') {
                    openEditModal(data);
                } else if (obj.event === 'delete') {
                    layer.confirm('确定要删除此分类吗？', function () {
                        fetch(`/api/categories/${data.id}`, {
                            method: 'DELETE',
                            headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')}
                        }).then(res => res.json()).then(res => {
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                loadCategoryData();
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        });
                    });
                }
            });

            // 编辑分类弹窗
            function openEditModal(data) {
                layer.open({
                    type: 1,
                    title: '编辑分类',
                    area: ['500px', '300px'],
                    content: `
                <form class="layui-form" id="editCategoryForm" style="padding: 20px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" required lay-verify="required" value="${data.name}" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">描述</label>
                        <div class="layui-input-block">
                            <input type="text" name="description" value="${data.description}" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="submitEdit">保存</button>
                            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                        </div>
                    </div>
                </form>
            `
                });

                form.render();
                form.on('submit(submitEdit)', function () {
                    const formData = new FormData(document.getElementById('editCategoryForm'));
                    fetch(`/api/categories/${data.id}`, {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer ' + localStorage.getItem('token')
                        },
                        body: formData
                    }).then(res => res.json()).then(res => {
                        if (res.code === 0) {
                            layer.msg('更新成功');
                            layer.closeAll();
                            loadCategoryData();
                        } else {
                            layer.msg(res.msg || '更新失败');
                        }
                    });
                    return false;
                });
            }
        });
    </script>

    <!-- 工具栏模板 -->
    <script type="text/html" id="operationBar">
        <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</button>
    </script>
{% endblock %}
